package com.shengruan.admin.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import com.shengruan.admin.jdbc.ProductClassJdbc;
import com.shengruan.admin.jdbc.ProductJdbc;
import com.shengruan.admin.jdbc.UserFavoritesJdbc;
import com.shengruan.admin.vo.Admin;
import com.shengruan.admin.vo.Product;
import com.shengruan.admin.vo.ProductClass;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.framework.pager.Pager;
import com.shengruan.index.action.AuctionUtil;
import com.shengruan.servlet.ServletUtils;
import com.shengruan.user.action.AutoAuctionUtil;
import com.shengruan.user.jdbc.AutoAuctionJdbc;

public class ProductAction extends BaseAction {

    private ProductClassJdbc productClassJdbc = (ProductClassJdbc)this.getJdbc(ProductClassJdbc.class);
    private ProductJdbc productJdbc = (ProductJdbc)this.getJdbc(ProductJdbc.class);

    /**
     * 向上
     * @throws Exception
     */
    public void up() throws Exception {

        String id = this.input("id");
        String status = this.input("status");

        Product nextProduct = this.productJdbc.next(Integer.valueOf(id));
        if(null != nextProduct) {
            int nextSort = nextProduct.getSort();

            Product product = this.productJdbc.getById(Integer.valueOf(id));
            int sort = product.getSort();

            product.setSort(nextSort);
            nextProduct.setSort(sort);

            this.productJdbc.update(product);
            this.productJdbc.update(nextProduct);
            
            reflashFromCache();
        }
        this.redirect("/admin/product/product-list.ac?status=" + status);
    }

    /**
     * 向下
     * @throws Exception
     */
    public void down() throws Exception {
        String id = this.input("id");
        String status = this.input("status");

        Product previousProduct = this.productJdbc.previous(Integer.valueOf(id));
        if(null != previousProduct) {
            int previousSort = previousProduct.getSort();

            Product product = this.productJdbc.getById(Integer.valueOf(id));
            int sort = product.getSort();

            product.setSort(previousSort);
            previousProduct.setSort(sort);

            this.productJdbc.update(product);
            this.productJdbc.update(previousProduct);
            
            reflashFromCache();
        }

        this.redirect("/admin/product/product-list.ac?status=" + status);
    }

    public void init() throws Exception {
        List<ProductClass> productClassList = this.productClassJdbc.getList();
        this.setRequest("productClassList", productClassList);
        this.forward("/admin/product/product-edit.jsp");
    }

    public void delete() throws Exception {
        String id = this.input("id");
        String status = this.input("status");

        productJdbc.deleteById(Integer.valueOf(id));
        this.setRequest(Constants.MESSAGE, "删除商品成功。");
        reflashFromCache();
        this.redirect("/admin/product/product-list.ac?status=" + status);
    }

    /****
     * reflashFromCache
     * @throws Exception
     */
    public void reflashFromCache(){
    	for (ProductClass productClass : Constants.productClassList)
            Constants.PRODUCT_MENU_LIST.put(productClass.getId().toString(),productJdbc.getList(productClass.getId().toString(),null,0));
        this.request.getSession().getServletContext().setAttribute(Constants.PRODUCT_MENU_MAP,Constants.PRODUCT_MENU_LIST);
    	
    }

    public void getById() throws Exception {
        String id = this.input("id");
        String status = this.input("status");
        Product product = productJdbc.getById(Integer.valueOf(id));
        this.setRequest("product", product);
        List<ProductClass> productClassList = this.productClassJdbc.getList();
        this.setRequest("productClassList", productClassList);
        this.setRequest("status", status);
        this.forward("/admin/product/product-edit.jsp");
    }


    public void list() throws Exception {

        String name = this.input("name");
        String classId = this.input("classId");
        String status = this.input("status");

        int currentPage = 1;
		try {
			currentPage = Integer.parseInt(this.input("currentPage"));
		} catch(Exception ex) { }

		Pager pager = new Pager(currentPage,productJdbc.getRows(name, classId, null, status),30);
		List<Product> productList = productJdbc.findWithPage(currentPage, 30,name, classId, null, status);

        this.setRequest("name", name);
		this.setRequest("pager", pager);
		this.setRequest("productList", productList);
		this.setRequest("status", status);
        this.forward("/admin/product/product-list.jsp");
    }

    public void add() throws Exception {
        Product product = new Product();
        //请求数据是不是使用multipart/form-data编码的
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String imgName = "";
        String status = null;
        int index=0;
        String imagePath = "";
		if(isMultipart){
			// 创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
			try {
				// 使用处理器解析请求，获取到文件项的列表
				List items = upload.parseRequest(request);
				int size = items == null ? 0 : items.size();
				index++;
				for(int i = 0; i < size; i++){ //处理每个文件项
					
					FileItem fileItem = (FileItem)items.get(i);
					if (fileItem.isFormField()) { //如果普通的表单域
						String name = fileItem.getFieldName();
					    String value = fileItem.getString();

                        if("name".equals(name)) product.setName(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("classId".equals(name))  product.setClassId(Integer.valueOf(value));
                        if("dimension".equals(name))  product.setDimension(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("globalLimited".equals(name))  product.setGlobalLimited(value);
                        if("description".equals(name))  product.setDescription(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        //if("effectiveAuctionTime".equals(name))  product.setEffectiveAuctionTime(DateUtils.parseDate(value, new String[]{"yyyy-MM-dd HH:mm:ss"}).getTime());
                        //if("effectiveAuctionTime".equals(name))  product.setEffectiveAuctionTime(Long.valueOf(value));
                        //if("auctionBeginTime".equals(name))  product.setAuctionBeginTime(DateUtils.parseDate(value, new String[]{"yyyy-MM-dd HH:mm:ss"}).getTime());
                        if("auctionTactics".equals(name)) product.setAuctionTactics(Integer.valueOf(value));
                        if("specification".equals(name)) product.setSpecification(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("material".equals(name)) product.setMaterial(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("price".equals(name)) product.setPrice(value);
                        //if("status".equals(name)) status = value;
				    } else { //表单文件域
				    	String fieldName = fileItem.getFieldName(); //文件域的名
				        String fileName = fileItem.getName(); //上传的文件名
				        if(fileName!=null&&!"".equals(fileName)) {
				        	  //获取文件存放目录的全路径名
	                        String basePath = null;
	                        if("smallPic".equals(fieldName)){
					            basePath= request.getSession().getServletContext().getRealPath("uploadfiles/product/smallPic");
	                        }else {
	                            basePath= request.getSession().getServletContext().getRealPath("uploadfiles/product/pic");
	                        }
					        //System.out.println("上传文件的存放路径："+ basePath);
					        //把文件写到目的地
					        //File fullFile = new File(fileName.getName());
					        String suffix = fileName.substring(fileName.lastIndexOf("."));
					        imgName = generateFileName(index) + suffix;
					        File uploadedFile = new File(basePath, imgName);
					        fileItem.write(uploadedFile);

	                        if("smallPic".equals(fieldName)){
	                            product.setSmallPic(imgName);
	                        }else {

                                imagePath += imgName + ",";

	                            /*if(null != product.getImagePath())
	                                product.setImagePath(product.getImagePath() + "," + imgName);
	                            else
	                                product.setImagePath(imgName);*/
	                        }
				        } else {
                            if(!"smallPic".equals(fieldName)){
                                if(!"upload4".equals(fieldName))  imagePath = imagePath + ",";
                            }
                        }

                      
				    }
				}

			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

            if(null != imagePath)
                product.setImagePath(imagePath);

            Admin admin = (Admin)ServletUtils.getSessionAttribute(request, Constants.ADMIN);
            product.setAuctionStatus(Constants.PRODUCT_AUCTION_STATUS_AVAILABLE);//即将开始
            product.setIsvalid(Constants.STATUS_ACTIVE);//不可用,下架
            product.setAdminId(Integer.valueOf(admin.getId()));
            product.setCreationTime(System.currentTimeMillis());
            product.setSort(this.productJdbc.getMaxSort());
            productJdbc.save(product);

            reflashFromCache();

            this.setRequest(Constants.MESSAGE, "添加商品成功。");
            this.redirect("/admin/product/product-list.ac");
		}else{
			//报错
            this.setRequest(Constants.MESSAGE, "添加商品失败。");
            this.redirect("/admin/product/product-list.ac");
		}
    }



    public void edit() throws Exception {
        Product product = null;
        //请求数据是不是使用multipart/form-data编码的
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String imgName = "";
        String status = null;
        int index = 0;

        String[] imagePathArray = null;
		if(isMultipart){
			// 创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
			try {
				// 使用处理器解析请求，获取到文件项的列表
				List items = upload.parseRequest(request);
				int size = items == null ? 0 : items.size();
				
				for(int i = 0; i < size; i++){ //处理每个文件项
					index++;
					FileItem fileItem = (FileItem)items.get(i);
					if (fileItem.isFormField()) { //如果普通的表单域
						String name = fileItem.getFieldName();
					    String value = fileItem.getString();
                        if("id".equals(name)) {
                            product = productJdbc.getById(Integer.valueOf(value));
                            imagePathArray = StringUtils.splitPreserveAllTokens(product.getImagePath(), ",");
                        }
                        if("name".equals(name)) product.setName(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("classId".equals(name))  product.setClassId(Integer.valueOf(value));
                        if("dimension".equals(name))  product.setDimension(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("globalLimited".equals(name))  product.setGlobalLimited(value);
                        //if("officialPrice".equals(name))  product.setOfficialPrice(Double.valueOf(value));
                        //if("priceCap".equals(name))  product.setPriceCap(Double.valueOf(value));
                        if("description".equals(name))  product.setDescription(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        //if("effectiveAuctionTime".equals(name))  product.setEffectiveAuctionTime(Long.parseLong(value));
                        //if("auctionBeginTime".equals(name))  product.setAuctionBeginTime(DateUtils.parseDate(value, new String[]{"yyyy-MM-dd HH:mm:ss"}).getTime());
                        if("specification".equals(name)) product.setSpecification(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("material".equals(name)) product.setMaterial(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("price".equals(name)) product.setPrice(value);
                        if("sort".equals(name)) product.setSort(Integer.valueOf(value));
                        //if("status".equals(name)) status = value;

				    } else { //表单文件域
				    	String fieldName = fileItem.getFieldName(); //文件域的名
				        String fileName = fileItem.getName(); //上传的文件名
                        if(StringUtils.isNotEmpty(fileName)) {
				       

				        //获取文件存放目录的全路径名
				        String basePath = null;
                        if("smallPic".equals(fieldName)){
				            basePath= request.getSession().getServletContext().getRealPath("uploadfiles/product/smallPic");
                        }else {
                            basePath= request.getSession().getServletContext().getRealPath("uploadfiles/product/pic");
                        }
				        //System.out.println("上传文件的存放路径："+ basePath);
				        //把文件写到目的地
				        //File fullFile = new File(fileName.getName());
				        String suffix = fileName.substring(fileName.lastIndexOf("."));
				        imgName = generateFileName(index) + suffix;
				        File uploadedFile = new File(basePath, imgName);
				        fileItem.write(uploadedFile);

                        if("smallPic".equals(fieldName)){
                            product.setSmallPic(imgName);
                        }else {
                             //imagePath += imgName + ",";
                            /*if(null != imagePath){
                                imagePath = imagePath + "," + imgName;
                            }else{
                               imagePath = imgName;
                            }*/
                            if("upload1".equals(fieldName)) imagePathArray[0] = imgName;
                            if("upload2".equals(fieldName)) imagePathArray[1] = imgName;
                            if("upload3".equals(fieldName)) imagePathArray[2] = imgName;
                            if("upload4".equals(fieldName)) imagePathArray[3] = imgName;
                        }
                            
                        }
				    }
				}
			

			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}


            String imagePathStr = "";
            for (int i = 0; i < imagePathArray.length; i++) {
                if (i == imagePathArray.length - 1) {//拼接时，不包括最后一个,字符
                    imagePathStr += imagePathArray[i];
                } else {
                    imagePathStr += imagePathArray[i] + ",";
                }
            }



            if(StringUtils.isNotEmpty(imagePathStr))
                product.setImagePath(imagePathStr);

            Admin admin = (Admin)ServletUtils.getSessionAttribute(request, Constants.ADMIN);
            product.setAdminId(admin.getId());
            productJdbc.update(product);

            reflashFromCache();
            this.setRequest(Constants.MESSAGE, "修改商品成功。");
            this.redirect("/admin/product/product-list.ac");
		}else{
			//报错
            this.setRequest(Constants.MESSAGE, "修改商品失败。");
            this.redirect("/admin/product/product-list.ac");
		}
    }

    public void changeIsvalid() throws Exception {
        String id = this.input("id");
        Product product = productJdbc.getById(Integer.valueOf(id));
        String status = this.input("status");

        if (product.getIsvalid() == Constants.STATUS_INACTIVE) {
            product.setIsvalid(Constants.STATUS_ACTIVE);
            this.setRequest(Constants.MESSAGE, "商品上架成功。");
            AuctionUtil.addProduct(product);
        } else {
            product.setIsvalid(Constants.STATUS_INACTIVE);
            this.setRequest(Constants.MESSAGE, "商品下架成功。");
        }
        productJdbc.updateIsvalid(id, product.getIsvalid());
        //productJdbc.intiMapFromDatabase();
        reflashFromCache();
        this.redirect("/admin/product/product-list.ac?status=" + status);
    }


    /**
	 * 使用当前时间值来产生一个唯一的文件名
	 * @return
	 */
	private static String generateFileName(int index){
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+"-"+index;
	}
}
